import { Component, OnInit } from '@angular/core';
import {Path} from "../../../../portal/admin/admin-breadcrumb/breadcrumb";
import {PageSubject} from "../../../../util/page-subject";
import {AirqualityCompareService} from "./airquality-compare.service";
import {OneDialogService} from "../../../../widgets/one-dialog/one-dialog.service";
import {ResponseUtil} from "../../../../util/response-util";
import {MsgResult} from "../../../../models/msg-result";
import {MsgConstants} from "../../../../constants/constants";

declare var $;
declare var echarts;
declare var moment;

@Component({
  selector: 'app-airquality-compare',
  templateUrl: './airquality-compare.component.html',
  styleUrls: ['./airquality-compare.component.css']
})
export class AirqualityCompareComponent implements OnInit {
  config;echartDataObj;
  constructor(
    private pageSubject : PageSubject,
    private AirqualityCompareService : AirqualityCompareService,
    private responseUtil :ResponseUtil,
    private dialogService: OneDialogService,
  ) { }

  ngOnInit() {
    this.pushPage();
    this.siteButtonData();
    this.initTime();


  }

  //面包屑导航
  pushPage() {
    let path = new Path("数据研判", "");
    this.pageSubject.pushPage("空气质量对比", "", path);
  }

  //   站点按钮数据
  siteButtonData(){
    this.AirqualityCompareService.getUserSiteData().subscribe(
      result => this.responseUtil.success(result,this.siteButtonDataResult),
      message => this.responseUtil.error(message)
    );
  }
  private siteButtonDataResult = (result: MsgResult) =>{
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.siteButtonDataDataTree(result.data);
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }
  //站点按钮
  siteButtonDataDataTree(data){
    let siteHtml = " ";
    let localSite = [
      {"name":"nationalSite","type":"national","chinese":"国控站"},
      {"name":"provinceSite","type":"province","chinese":"省控站"},
      {"name":"smallAirSite","type":"smallAir","chinese":"微型站"}
    ];
    $.each(localSite,function (j,siteList) {
      $.each(data,function (i,list) {
        if(list==siteList.name){
          siteHtml+='<div class="btn btn-default" id="'+siteList.name+'" data-type="'+siteList.type+'">'+siteList.chinese+'</div>';
        }
      });
    });
    if(siteHtml){
      $(".user_site_button").html(siteHtml);
      $(".user_site_button").find(".btn:first").addClass("active");
      this.initBtnEvent();
      this.initSiteData();
      this.initBtnStyle();

    }else{
      $(".user_site_list").html("暂无数据");
    }

  };




//初始化数据
  initSiteData(){
    this.listNationSiteData();
    this.listSmallSiteData();
  }

  //按钮样式
  initBtnStyle(){
    //改变input样式
    $('input').iCheck({
      checkboxClass: 'icheckbox_minimal-green',
      radioClass: 'iradio_minimal-green',
      increaseArea: '20%' // optional
    });

    $("#compareChart").css({"width":"100%","height":$(window.innerHeight)[0]-330+"px"});

    //按钮点击事件
    $(".btn-group .btn:not(.btn-disabled)").click(function(){
      $(this).addClass("active").siblings(".active").removeClass("active");
    });

    //点击站点列表
    $(".one-inline-btn").click(function(){
      $(this).find(".dropdown-menu").show();
    }).mouseleave(function(){
      $(this).find(".dropdown-menu").hide();
    });


    //点击站点列表中的删除图标
    $(".one-inline-container").on("click",".btn>.glyphicon-remove",function(){
      $(this).parent().remove();
      if($(".one-inline-container>.btn").length<5){
        $('.list-inline input').iCheck('enable');
      }else{
        $('.list-inline .icheckbox_minimal-green:not(.checked) input').iCheck('disable');
      }
      var btnId = $(this).parent().attr("id");
      $(".dropdown-menu label").each(function(){
        var  id = $(this).find("input").attr("id");
        if( btnId == id){
          $(this).find("input").iCheck('uncheck');
        }
      });
    });
  }

  //初始化日期插件
  initTime(){
  this.config = {
  timePicker:true,
  timePickerIncrement:5,
  timePicker24Hour:true,
  parentEl:$(".wrapper"),
  maxDate:new Date(),
  locale:{
    format:"YYYY-MM-DD HH:00",
    separator: " 至 ",
    applyLabel : '确定',
    cancelLabel : '取消',
    fromLabel: '从',
    toLabel: '到',
    weekLabel: 'W',
    customRangeLabel: 'Custom Range',
    daysOfWeek:["日","一","二","三","四","五","六"],
    monthNames: ["一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"],
    firstDay:1
  },
  startDate:moment().subtract(1,"d").subtract(1,"h").format("YYYY-MM-DD HH")+":00",
  endDate: moment().subtract(1,"h").format("YYYY-MM-DD HH")+":00"
};
  $("#airCompareDate").daterangepicker(this.config);
}

//点击事件
  initBtnEvent(){
    //点击站点类型
    $(".dropdown-menu>.one-btn-data-type").on("click",".btn",function(){
      var id = $(this).data("type");
      console.log(id);
      $("#"+id).show().siblings(".list-inline").hide();
    });

    //查询站点
    $("#search-site").bind("input propertychange",function () {
      let searchSiteVal = $("#search-site").val();
        if(searchSiteVal){
          $(".dropdown-menu label").each(function(){
            var text = $(this).text();
            if(text.indexOf(searchSiteVal)!=-1){
              $(this).parent().show();
            }else{
              $(this).parent().hide();
            }
          })
        }else{
          $(".dropdown-menu label").parent().show();
        }
    })

    //阻止查询enter冒泡
    $("#searchPollute").keydown(function(e){
      if(e.keyCode == "13"){
        e.preventDefault();
      }
    }).change(function(e){
      e.preventDefault();
    });

    //点击选择日期
    $(".oneDay").click(function(){
      this.config.locale.format="YYYY-MM-DD HH:00";
      this.config.startDate =moment().subtract(2,"d").subtract(1,"h").format("YYYY-MM-DD HH")+":00";
      this.config.endDate = moment().subtract(1,"d").subtract(1,"h").format("YYYY-MM-DD HH")+":00";
    $("#airCompareDate").daterangepicker(this.config);
    $("#dayData").hide().removeClass("active");
    $("#hourData").show().addClass("active");
  }.bind(this));
    $(".weekDay").click(function(){
    if($(".dataType").find(".active").attr("id") == "dayData"){
      this.config.locale.format="YYYY-MM-DD";
      this.config.startDate = moment().subtract(1,"w").subtract(1,"d").format("YYYY-MM-DD");
      this.config.endDate = moment().subtract(1,"d").format("YYYY-MM-DD");
      $("#airCompareDate").daterangepicker(this.config);
    }else{
      this.config.locale.format="YYYY-MM-DD HH:00";
      this.config.startDate = moment().subtract(1,"w").subtract(1,"d").subtract(1,"h").format("YYYY-MM-DD HH")+":00";
      this.config.endDate = moment().subtract(1,"d").subtract(1,"h").format("YYYY-MM-DD HH")+":00";
      $("#airCompareDate").daterangepicker(this.config);
    }
    $("#dayData").show();
    $("#hourData").show();
  }.bind(this));
    $(".monthDay").click(function(){
    if($(".dataType").find(".active").attr("id") == "dayData"){
      this.config.locale.format="YYYY-MM-DD";
      this.config.startDate = moment().subtract(1,"M").subtract(1,"d").format("YYYY-MM-DD");
      this.config.endDate = moment().subtract(1,"d").format("YYYY-MM-DD");
      $("#airCompareDate").daterangepicker(this.config);
    }else{
      this.config.locale.format="YYYY-MM-DD HH:00";
      this.config.startDate = moment().subtract(1,"M").subtract(1,"d").subtract(1,"h").format("YYYY-MM-DD HH")+":00";
      this.config.endDate = moment().subtract(1,"d").subtract(1,"h").format("YYYY-MM-DD HH")+":00";
      $("#airCompareDate").daterangepicker(this.config);
    }
    $("#hourData").show();
    $("#dayData").show();
  }.bind(this));
    $(".yearDay").click(function(){
      this.config.locale.format="YYYY-MM-DD";
      this.config.startDate = moment().subtract(1,"y").subtract(1,"d").format("YYYY-MM-DD");
      this.config.endDate = moment().subtract(1,"d").format("YYYY-MM-DD");
    $("#airCompareDate").daterangepicker(this.config);
    $("#hourData").hide().removeClass("active");
    $("#dayData").show().addClass("active");
  }.bind(this));
    $(".hour").click(function(){

    let startTime;
    let timeBtn = $(".timeBtn").find(".active").attr("id");
    if(timeBtn=="oneDay"){
      startTime = moment().subtract(2,"d").subtract(1,"h").format("YYYY-MM-DD HH")+":00";
    }else if(timeBtn=="weekDay"){
      startTime = moment().subtract(1,"w").subtract(1,"d").subtract(1,"h").format("YYYY-MM-DD HH")+":00";
    }else if(timeBtn=="monthDay"){
      startTime = moment().subtract(1,"m").subtract(1,"d").subtract(1,"h").format("YYYY-MM-DD HH")+":00";
    }
    this.config.locale.format="YYYY-MM-DD HH:00";
    this.config.startDate =startTime;
    this.config.endDate =  moment().subtract(1,"d").subtract(1,"h").format("YYYY-MM-DD HH")+":00";
  $("#airCompareDate").daterangepicker(this.config);
}.bind(this));
    $(".day").click(function(){
    let startTime;
    let timeBtn = $(".timeBtn").find(".active").attr("id");
    if(timeBtn=="oneDay"){
      startTime = moment().subtract(2,"d").format("YYYY-MM-DD");
    }else if(timeBtn=="weekDay"){
      startTime = moment().subtract(1,"w").subtract(1,"d").format("YYYY-MM-DD");
    }else if(timeBtn=="monthDay"){
      startTime = moment().subtract(1,"M").subtract(1,"d").format("YYYY-MM-DD");
    }
    this.config.locale.format="YYYY-MM-DD";
    this.config.startDate = startTime;
    this.config.endDate = moment().subtract(1,"d").format("YYYY-MM-DD");
  $("#airCompareDate").daterangepicker(this.config);
}.bind(this));
    $(".search").click(function () {
      this.chartData();
    }.bind(this));
  }

  //省控/国控站下拉数据
  listNationSiteData(){
    this.AirqualityCompareService.getNationSiteData().subscribe(
      result => this.responseUtil.success(result,this.getNationSiteDataResult),
      message => this.responseUtil.error(message)
    );
  }
  private getNationSiteDataResult = (result: MsgResult) =>{
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.getNationSiteDataTree(result.data);
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }
  private getNationSiteDataTree(data){
    if(data == null){
      $(".dropdown-menu .list-inline").html("暂无数据");
      $("#compareChart").html("<div class='one-message-null'>暂无数据</div>");
    }else{
      console.log("省控站数据加载成功");
      $(".one-data-loadState").hide();
      this.dropDownData(data,"allNationalSite");
      this.chartData();
    }
  }

  //微型站下拉数据
  listSmallSiteData(){
    this.AirqualityCompareService.getSmallSiteData().subscribe(
      result => this.responseUtil.success(result,this.getSmallSiteDataResult),
      message => this.responseUtil.error(message)
    );
  }
  private getSmallSiteDataResult = (result: MsgResult) =>{
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.getSmallSiteDataResultTree(result.data);
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }
  private getSmallSiteDataResultTree(data){
    if(data == null){
      $(".dropdown-menu .list-inline").html("暂无数据");
      $("#compareChart").html("<div class='one-message-null'>暂无数据</div>");
    }else{
      console.log("微型站数据加载成功");
      this.dropDownData(data,"smallAirSite");
    }
  }

  //请求下拉列表中的数据
  dropDownData(dropDatas,pointType){
  var dropNationHtml = "";
  var dropProvinceHtml = "";
  var dropSmallAirHtml = "";
  $.each(dropDatas,function(index,dropData){
    if(dropData.siteTypeCode == "001"){
      dropNationHtml += '<li><label><input type="checkbox" id='+dropData.siteCode+'>' + dropData.siteName + '</label></li>';
    }else if(dropData.siteTypeCode == "002"){
      dropProvinceHtml += '<li><label><input type="checkbox" id='+dropData.siteCode+'>' + dropData.siteName + '</label></li>';
    }else if(dropData.siteTypeCode == "004"){
      dropSmallAirHtml += '<li><label><input type="checkbox" id='+dropData.siteCode+'>' + dropData.siteName + '</label></li>';
    }
  });
  if(pointType == "allNationalSite"){
    dropNationHtml == ""? $("#national").html("暂无数据"):$("#national").html(dropNationHtml);
    dropProvinceHtml == "" ?$("#province").html("暂无数据"):$("#province").html(dropProvinceHtml);
  }else if(pointType == "smallAirSite"){
    dropSmallAirHtml == ""?$("#smallAir").html("暂无数据"):$("#smallAir").html(dropSmallAirHtml);
  }
  //改变input样式
  $('input').iCheck({
    checkboxClass: 'icheckbox_minimal-green',
    radioClass: 'iradio_minimal-green',
    increaseArea: '20%' // optional
  });
  //点击下拉列表中的元素
  $('.list-inline input').on('ifChecked', function(e){
    var text = $(this).parent().parent().text();
    var btnId = $(this).attr("id");
    var btnHtml = '<div class="btn btn-success" id='+btnId+'>'+text+' <i class="glyphicon glyphicon-remove"></i></div>';
    $(".one-inline-container").append(btnHtml);
  }).on('ifUnchecked', function(e){
    if($(".one-inline-container>.btn").length<=5){
      $(this).parent().parent().parent().parent().find(".icheckbox_minimal-green input").iCheck('enable');
    }
    var text = $.trim($(this).parent().parent().text());
    $(".one-inline-container>.btn").each(function(){
      var btnText = $.trim($(this).text());
      if(btnText==text){
        $(this).remove();
      }
    });
  }).on("ifClicked",function(){
    if($(".one-inline-container>.btn").length>=4){
      $(this).parent().parent().parent().parent().parent().find(".icheckbox_minimal-green:not(.checked) input").iCheck('disable');
      $(this).parent().parent().iCheck('enable');
    }else{
      $(this).parent().parent().parent().parent().parent().find(".icheckbox_minimal-green input").iCheck('enable');
    }
  });
  //初始化站点选择
  $("#national li:first-child,#national li:nth-child(2)").find("input").iCheck('check');
  var btnText1 = $("#national li:first-child").find("label").text();
  var btnText2 = $("#national li:nth-child(2)").find("label").text();
  var btnId1 = $("#national li:nth-child(1)").find("input").attr("id");
  var btnId2 = $("#national li:nth-child(2)").find("input").attr("id");
  var initBtnHtml = '<div class="btn btn-success" id='+btnId1+'>'+btnText1+' <i class="glyphicon glyphicon-remove"></i></div>'+'<div class="btn btn-success" id='+btnId2+'>'+btnText2+' <i class="glyphicon glyphicon-remove"></i></div>';
  $(".one-inline-container").html(initBtnHtml);
}

//图表数据处理
  chartData(){
    let rangeTime = $("#airCompareDate").val();
    let dataType = $(".dataType").find(".active").attr("id");
    let startTime;let endTime;
    if(dataType=="hourData"){
      startTime = $.trim(rangeTime.split("至")[0])+":00";
      endTime = $.trim(rangeTime.split("至")[1])+":00";
    }else{
      startTime = $.trim(rangeTime.split("至")[0])+" 00:00:00";
      endTime = $.trim(rangeTime.split("至")[1])+" 00:00:00";
    }

    let qualityFactor = $(".factor").find(".active").attr("id");
    console.log(qualityFactor);
    if(!qualityFactor){
      qualityFactor ="AQI";
    }
    let checkedSiteListObj = [];
    $(".one-inline-container>.btn").each(function(){
      var id = $(this).attr("id");
      checkedSiteListObj.push(id);
    });
    let checkedSiteCodes = checkedSiteListObj.join(",");
    this.echartDataObj={"qualityFactor":qualityFactor,"dataType":dataType,"checkedSiteCodes":checkedSiteCodes,"startTime":startTime,"endTime":endTime}
    this.airQualityCompareData(this.echartDataObj);
}

  //图表数据
  airQualityCompareData(obj){
    this.AirqualityCompareService.getAirQualityCompareData(obj).subscribe(
      result => this.responseUtil.success(result,this.getAirQualityCompareResult),
      message => this.responseUtil.error(message)
    );
  }
  private getAirQualityCompareResult = (result: MsgResult) =>{
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.getAirQualityCompareResultTree(result.data);
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }
  private getAirQualityCompareResultTree(data){
    if(data == null){
      $("#compareChart").html("<div class='one-message-null'>暂无数据</div>");
    }else{
      console.log("图表数据加载成功");
      console.log(data);
      this.chartRender(data);
    }
  }

//    图表
chartRender(chartList) {
  var compareChart = echarts.init(document.getElementById('compareChart'));
  //图表配置信息
  var option = {
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data:chartList.siteNameList
    },
    xAxis: {
      type: 'category',
      nameGap:"20",
      name: "日期",
      nameLocation:"start",
      boundaryGap: false,
      data: chartList.timeList[0]
    },
    yAxis: {
      name: "指数",
      type: 'value'
    },
    series: []
  };
  //series中的内容
  $.each(chartList.siteNameList,function(index,nameList){
    // let  seriesList = {};
    // this.seriesList.type = "line";
    // this.seriesList.smooth = true;
    // this.seriesList.name = nameList;
    // this.seriesList.data = chartList.dataList[index];
    option.series.push({"type":"line","smooth":true,"name":nameList,"data":chartList.dataList[index]})
  });
  compareChart.setOption(option);
}

}
